package com.nakamachizu.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.TimeZoneLocator;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.nakamachizu.collection.ApiKeyMap;
import com.nakamachizu.meta.MemberDataMeta;
import com.nakamachizu.model.MemberData;
import com.nakamachizu.util.ErrorsUtil;
import com.nakamachizu.util.ForwardUtil;

public class EditMemberController extends Controller {

    private String name;
    private String comment;
    private String id;
    private String password;
    
    private Calendar now;
    
    protected List<String> messages = new ArrayList<String>();
    
    @Override
    public Navigation run() throws Exception {
        String keyStr = "";
        
        init();
        
        if(validate()){
            Key key = KeyFactory.stringToKey(id);
            MemberData mem = Datastore.get(MemberDataMeta.get(), key);
            keyStr = mem.getMapDataRef().getModel().getAccessKey();
            requestScope("key", keyStr);
            requestScope("serverName", request.getServerName());
            
            if(password.equals(mem.getEditPassword())){
               mem.setName(name);
               mem.setComment(comment);
               mem.setModifyDate(now.getTime());
               mem.setIpAddress(request.getRemoteAddr());
               Datastore.put(mem);
            }else{
                requestScope("key", keyStr);
                requestScope("apiKey", ApiKeyMap.API_KEY_MAP.get(request.getServerName()));
                ErrorsUtil.putErrors(errors, request, "message.error.invalidpassword", "invalid_password");
                return forward(ForwardUtil.forwardJsp("map.jsp"));
            }
        }
        
        return redirect("/map?key=" + keyStr);
    }
    
    private void init(){
        name = requestScope("name");
        comment = requestScope("comment");
        password = requestScope("password");
        id = requestScope("id");
        
        now = Calendar.getInstance(TimeZoneLocator.get());
    }
    
    protected boolean validate() {
        boolean result = false;
        Validators v = new Validators(request);
        v.add("password", v.required());
        v.add("name", v.required());
        v.add("comment", v.required());
        v.add("id", v.required());

        result = v.validate();
        
        return result;
    }
}
